<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-icon model-icon">
            <el-icon><Memo /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ modelCount }}</div>
            <div class="stat-label">数据模型</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-icon data-icon">
            <el-icon><Grid /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ totalRecords }}</div>
            <div class="stat-label">数据记录</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-icon db-icon">
            <el-icon><MostlyCloudy /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ databaseType }}</div>
            <div class="stat-label">数据库类型</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="stat-card">
          <div class="stat-icon api-icon">
            <el-icon><Share /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ apiCount }}</div>
            <div class="stat-label">API接口</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="dashboard-row">
      <el-col :xs="24" :lg="16">
        <el-card class="model-list-card">
          <template #header>
            <div class="card-header">
              <span>最近的数据模型</span>
              <el-button type="primary" size="small" @click="$router.push('/models/create')">
                创建模型
              </el-button>
            </div>
          </template>
          
          <el-table :data="models" style="width: 100%" v-loading="loading">
            <el-table-column prop="name" label="模型名称" />
            <el-table-column prop="displayName" label="显示名称" />
            <el-table-column label="字段数">
              <template #default="scope">
                {{ scope.row.fields.length }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="$router.push(`/data/${scope.row.name}`)"
                >
                  查看数据
                </el-button>
                <el-button 
                  size="small" 
                  @click="$router.push(`/models/${scope.row.id}/edit`)"
                >
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="8">
        <el-card class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <span>快速操作</span>
            </div>
          </template>
          
          <div class="quick-actions">
            <el-button type="primary" @click="$router.push('/models/create')">
              <el-icon><el-icon-plus /></el-icon>
              创建数据模型
            </el-button>
            
            <el-button type="success" @click="$router.push('/settings')">
              <el-icon><el-icon-setting /></el-icon>
              系统设置
            </el-button>
          </div>
          
          <div class="database-info">
            <h3>数据库信息</h3>
            <p><strong>类型:</strong> {{ databaseType }}</p>
            <template v-if="settings.databaseType === 'sqlite'">
              <p><strong>存储路径:</strong> {{ settings.databaseConfig.sqlite.storage }}</p>
            </template>
            <template v-else-if="settings.databaseType === 'mysql'">
              <p><strong>主机:</strong> {{ settings.databaseConfig.mysql.host }}</p>
              <p><strong>端口:</strong> {{ settings.databaseConfig.mysql.port }}</p>
              <p><strong>数据库:</strong> {{ settings.databaseConfig.mysql.database }}</p>
            </template>
            <template v-else-if="settings.databaseType === 'sqlserver'">
              <p><strong>服务器:</strong> {{ settings.databaseConfig.sqlserver.server }}</p>
              <p><strong>端口:</strong> {{ settings.databaseConfig.sqlserver.port }}</p>
              <p><strong>数据库:</strong> {{ settings.databaseConfig.sqlserver.database }}</p>
            </template>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useModelStore } from '../stores/model'
import { useSettingsStore } from '../stores/settings'
import { useRouter } from 'vue-router'
import api from '../api'

const router = useRouter()
const modelStore = useModelStore()
const settingsStore = useSettingsStore()

const models = computed(() => modelStore.models)
const loading = ref(true)
const error = ref(null)
const settings = computed(() => settingsStore.settings)

const modelCount = computed(() => models.value.length)
const totalRecords = ref(0)
const apiCount = computed(() => modelCount.value * 5) // 每个模型有5个API接口
const dbInfo = ref('SQLite')

const databaseType = computed(() => {
  switch (settings.value.databaseType) {
    case 'mysql':
      return 'MySQL'
    case 'sqlserver':
      return 'SQL Server'
    case 'sqlite':
    default:
      return 'SQLite'
  }
})

async function fetchSystemStatus() {
  try {
    // 获取系统设置
    try {
      const response = await api.getSettings()
      if (response && response.data && response.data.databaseType) {
        dbInfo.value = response.data.databaseType.toUpperCase()
      }
    } catch (settingsErr) {
      console.warn('获取系统设置失败:', settingsErr)
      // 继续执行，不中断整个流程
    }
    
    // 获取服务器状态
    try {
      const statusResponse = await fetch('/api/status')
      if (statusResponse.ok) {
        const statusData = await statusResponse.json()
        console.log('服务器状态:', statusData)
      } else {
        console.warn('获取服务器状态失败:', statusResponse.statusText)
      }
    } catch (statusErr) {
      console.warn('获取服务器状态失败:', statusErr)
      // 继续执行，不中断整个流程
    }
    
    // 计算总记录数
    let recordCount = 0
    
    // 确保模型数组有效
    if (Array.isArray(modelStore.models) && modelStore.models.length > 0) {
      for (const model of modelStore.models) {
        // 确保模型对象有效
        if (!model || !model.name) {
          console.warn('跳过无效的模型对象:', model)
          continue
        }
        
        try {
          const dataResponse = await api.getData(model.name, { pageSize: 1 })
          if (dataResponse && dataResponse.data && typeof dataResponse.data.total === 'number') {
            recordCount += dataResponse.data.total
          }
        } catch (err) {
          console.warn(`获取${model.name}记录数失败:`, err)
          // 继续处理下一个模型
        }
      }
    } else {
      console.warn('没有可用的模型数据')
    }
    
    totalRecords.value = recordCount
  } catch (err) {
    console.error('获取系统状态失败:', err)
    error.value = `获取系统状态失败: ${err.message}`
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  try {
    // 加载模型
    await modelStore.fetchModels()
    
    // 检查模型是否加载成功
    if (!Array.isArray(modelStore.models)) {
      throw new Error('模型数据无效')
    }
    
    console.log('成功加载模型:', modelStore.models.length)
    
    // 获取系统状态
    await fetchSystemStatus()
  } catch (err) {
    console.error('Dashboard初始化失败:', err)
    error.value = `Dashboard初始化失败: ${err.message}`
    loading.value = false
  }
})
</script>

<style scoped>
.dashboard {
  padding: 20px 0;
}

.dashboard-row {
  margin-top: 20px;
}

.stat-card {
  height: 100%;
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 20px;
}

.model-icon {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.data-icon {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.db-icon {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.api-icon {
  background-color: rgba(144, 147, 153, 0.1);
  color: #909399;
}

.stat-content {
  flex-grow: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.database-info {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.database-info h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
}

.database-info p {
  margin: 5px 0;
  color: #606266;
}

.loading-container,
.error-container {
  padding: 20px 0;
}
</style> 